<!-- 教学资源分类模块入口 -->
<template>
	<!-- v2必须包裹的盒子 -->
	<div class="theoretical-teaching-sort">
		<!-- 顶部操作栏 -->
		<div class="operation">
			<div class="op">
				<el-button
					@click="addCourseSort()"
					type="success"
					size="small"
				>
					<i class="el-icon-plus"></i>
					新增教学资源分类
				</el-button>
				<el-button
					@click="multipleDelete()"
					type="danger"
					size="small"
				>
					<i class="el-icon-delete"></i>
					批量删除
				</el-button>
				<el-button
					@click="exportCourseExcel()"
					type="primary"
					size="small"
				>
					<i class="el-icon-paperclip">
					</i>
					导出
				</el-button>
			</div>
			<div class="collect">
				<div class="collect-item">
					<!-- <label for=""> 
						教学分类名称: 
					</label> -->
					<el-input
						placeholder="请输入教学分类名称"
						v-model="courseSortName"
						style="width: 200px"
					>
					</el-input>
				</div>
				<div class="collect-item">
					<el-button
						@click="filter()"
						type="primary"
						size="small"
					>
						<i class="el-icon-search">
						</i>
						查询
					</el-button>
					<el-button
						@click="refresh()"
						type="primary"
						size="small"
					>
						<i
							class="el-icon-refresh-left"></i>
						刷新
					</el-button>
				</div>
			</div>
		</div>
		<!-- 数据展示 -->
		<el-table
			:data="courseSortList"
			element-loading-text="Loading"
			border
			fit
			highlight-current-row
		>
			<el-table-column
				align="center"
				width="50"
			>
				<template
					slot="header"
					slot-scope="scope"
				>
					<el-checkbox
						v-model="isCheckedAll"
						@click="checkedAll"
					></el-checkbox>
				</template>
				<template slot-scope="scope">
					<el-checkbox
						v-model="scope.row.checked"
						@change="ifChecked(row)"
					></el-checkbox>
				</template>
			</el-table-column>
			<el-table-column
				align="center"
				label="教学分类ID"
				width="150"
			>
				<template slot-scope="scope">
					{{
						scope.row.sort_id + ""
					}}
				</template>
			</el-table-column>
			<el-table-column
				align="center"
				label="教学分类名称"
				width="150"
			>
				<template slot-scope="scope">
					{{
						scope.row.sort_name || "--"
					}}
				</template>
			</el-table-column>
			<el-table-column
				label="教学分类描述"
				align="center"
			>
				<template slot-scope="scope">
					{{
						scope.row.sort_desc || "--"
					}}
				</template>
			</el-table-column>
			<el-table-column
				align="center"
				label="操作"
				width="200"
			>
				<template slot-scope="scope">

					<el-button
						@click.native.prevent="editCourseSort(scope)"
						type="primary"
						size="small"
					>

						<i
							class="el-icon-edit"></i>
						编辑
					</el-button>
					<el-button
						@click.native.prevent="deleteCourseSort(scope)"
						type="danger"
						size="small"
					>
						<i
							class="el-icon-delete"></i>
						删除
					</el-button>

				</template>
			</el-table-column>
		</el-table>
		<!-- 分页器 -->
		<el-pagination
			v-if="courseSortList.length > 0"
			class="pagination"
			@size-change="handleSizeChange"
			@current-change="handleCurrentChange"
			:current-page="currentPage"
			:page-sizes="[10, 50, 100, 150]"
			:page-size="currentPageSize"
			layout="total, sizes, prev, pager, next, jumper"
			:total="courseSortList.length"
		>
		</el-pagination>
		<!-- 新增教学分类 -->
		<el-dialog
			title="新增教学分类"
			:visible.sync="addCourseSortData.dialogVisible"
			width="50%"
			:before-close="handleAddCourseSortDataClose"
		>
			<el-form
				ref="form"
				:model="addCourseSortData"
				label-width="80px"
			>
				<el-form-item
					style="font-size:16px"
					label="教学分类名称"
				>
					<el-input
						v-model="addCourseSortData.name"
					>
					</el-input>
				</el-form-item>
				<el-form-item label="教学分类描述">
					<el-input
						v-model="addCourseSortData.desc"
					>
					</el-input>
				</el-form-item>
			</el-form>
			<span
				slot="footer"
				class="dialog-footer"
			>
				<el-button
					type="warning"
					@click="handleAddCourseSortDataCancel()"
				>
					取 消
				</el-button>
				<el-button
					type="primary"
					@click="handleAddCourseSortDataConfirm()"
				>
					确 定
				</el-button>
			</span>
		</el-dialog>
		<!-- 编辑教学分类 -->
		<el-dialog
			title="编辑教学分类"
			:visible.sync="editCourseSortData.dialogVisible"
			width="50%"
			:before-close="handleEditCourseSortDataClose"
		>
			<el-form
				ref="form"
				:model="editCourseSortData"
				label-width="100px"
			>
				<el-form-item label="教学分类ID">
					<el-input
						v-model="editCourseSortData.id"
						disabled
					></el-input>
				</el-form-item>
				<el-form-item label="教学分类名称">
					<el-input
						v-model="editCourseSortData.name"
					>
					</el-input>
				</el-form-item>
				<el-form-item label="教学分类描述">
					<el-input
						v-model="editCourseSortData.desc"
					>
					</el-input>
				</el-form-item>
			</el-form>
			<span
				slot="footer"
				class="dialog-footer"
			>
				<el-button
					type="warning"
					@click="handleEditCourseSortDataCancel()"
				>
					取 消
				</el-button>
				<el-button
					type="primary"
					@click="handleEditCourseSortDataConfirm()"
				>
					确 定
				</el-button>
			</span>
		</el-dialog>
		<!-- 确认弹窗 -->
		<el-dialog
			:title="confirmDialogData.title"
			:visible.sync="confirmDialogData.dialogVisible"
			width="50%"
			:before-close="handleConfirmDialogClose"
		>
			<p>{{ confirmDialogData.content }}</p>
			<span
				slot="footer"
				class="dialog-footer"
			>
				<el-button
					type="warning"
					@click="handleEditConfirmDialogCancel()"
				>
					取 消
				</el-button>
				<el-button
					type="primary"
					@click="handleConfirmDialogConfirm()"
				>
					确 定
				</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
// 引入导出插件XLSX
import { saveAs } from "file-saver";
// 引入导出插件XLSX
import XLSX from "xlsx";
// 引入loading
import { Loading } from "element-ui";
// 引入请求
import request from "@/utils/request";

export default {
	data() {
		return {
			// 是否全选所有页
			isCheckedAll: false,
			// 选中的数据
			selectList: [],
			// 教学分类列表 全部数据，用于存储当前查询到的所有数据，方便分页功能
			courseSortList: [],
			// 教学分类名称
			courseSortName: "",
			// 筛选数据,用于存储当前筛选的数据
			filterData: [],
			// 当前页，默认第一页
			currentPage: 1,
			// 当前页大小，默认每页10条数据
			currentPageSize: 10,
			// 当前数据总数
			paginationTotal: 0,
			// 新增分类数据
			addCourseSortData: {
				dialogVisible: false,
				name: "",
				desc: "",
			},
			// 编辑分类数据
			editCourseSortData: {
				dialogVisible: false,
				id: "",
				name: "",
				desc: "",
			},
			/**
			 * @desc 确认弹窗数据
			 */
			confirmDialogData: {
				// 确认弹窗传入的标题
				title: "",
				// 控制弹窗开关变量
				dialogVisible: "",
				// 确认弹窗的问题
				content: "",
				from: "",
			},
		};
	},
	created() {
		// 模块初始化事件入口
		this.init();
	},
	methods: {
		/**
		 * @desc init
		 */
		init() {
			// 获取教学分类数据
			this.getCourseSortList();
		},
		/**
		 * @desc 获取教学分类数据
		 */
		getCourseSortList() {
			// loading 开启
			const loading = this.$loading({
				lock: true,
				text: "正在加载数据中，请耐心等待...",
				spinner: "el-icon-loading",
				background: "rgba(0, 0, 0, 0.7)",
			});
			let data = {};
			request({
				url: "/vue-admin-template/course/sort",
				method: "get",
				data,
			})
				.then((res) => {
					if (res.code === 20000) {
						if (typeof res.data === "object" && Object.keys(res.data)) {
							let temp = res.data.sort_list;
							// let arr = [];
							// // 去重
							// let ids = [];
							// temp.forEach((item) => {
							// 	if (ids.indexOf(item.sort_id) !== -1) {
							// 		ids.push(item.sort_id);
							// 		arr.push({
							// 			sort_id: item.sort_id,
							// 			sort_desc: item.sort_desc,
							// 		});
							// 	}
							// });
							// 排序
							// for (let i = 0; i < arr.length - 1; i++) {
							// 	for (let j = 1; j < arr.length - 1 - i; j++) {
							// 		if (arr[j] > arr[i]) {
							// 			// 交换位置
							// 			[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
							// 		}
							// 	}
							// }

							// console.log("排序结果：", arr);
							this.courseSortList = temp.sort((a, b) => {
								return parseInt(a.sort_id) - parseInt(b.sort_id);
							});
							this.courseSortList.forEach((item) => {
								// 给每一列数据添加，选择标识
								// 默认全部不选中
								item.checked = false;
								this.isCheckedAll = false;
							});
							// 关闭loading
							setTimeout(() => {
								loading.close();
							}, 500);
						} else {
							// 关闭loading
							setTimeout(() => {
								loading.close();
							}, 500);
						}
					} else {
						// 关闭loading
						setTimeout(() => {
							loading.close();
						}, 500);
					}
				})
				.catch((err) => {
					setTimeout(() => {
						this.$message({
							message: "接口错误",
							type: "error",
						});
					});
				});
		},
		/**
		 * @desc 单选事件
		 */
		ifChecked(row) {
			getCheckedRows();
		},
		/**
		 * @desc 全选事件
		 */
		checkedAll() {
			// 全选的一定是刚刚搜索出来的数据项
			this.filterData.forEach((item) => {
				item.checked = this.isCheckedAll;
			});
		},
		/**
		 * @desc 获取选中数据
		 */
		getCheckedRows(fromFilter) {
			var selectList = [];
			this.courseSortList.forEach((data) => {
				if (data.checked) {
					selectList.push(data);
				}
			});
			this.filterData.forEach((row) => {
				if (row.checked) {
					i++;
				}
			});

			if (i !== 0 && i == this.filterData.length) {
				this.isCheckedAll = true;
			} else {
				this.isCheckedAll = false;
			}

			if (!fromFilter) {
				this.selectList = selectList.sort((a, b) => {
					return parseInt(a.sort_id) - parseInt(b.sort_id);
				});
			}
		},
		/**
		 * @desc 获取用户选中的数据
		 */
		getSelectData() {
			return this.selectList;
		},
		/**
		 * @desc 新增教学分类
		 */
		addCourseSort() {
			// 打开新增分类弹窗
			this.addCourseSortData.dialogVisible = true;
		},
		/**
		 * @desc 确定添加教学分类
		 */
		handleAddCourseSortDataConfirm() {
			/* 
			1、判断当前表单项是否为空，不为空，提示用户，并且return
			2、数据校验完毕，请求接口
			*/
			/* 数据判空开始 */
			if (this.addCourseSortData.name == "") {
				this.$message({
					message: "教学分类名称不能为空。",
					type: "error",
				});
				return;
			}
			if (this.addCourseSortData.desc == "") {
				this.$message({
					message: "教学分类描述不能为空。",
					type: "error",
				});
				return;
			}
			/* 数据判空结束 */
			/* 开始请求接口 */
			// loading 开启
			const loading = this.$loading({
				lock: true,
				text: "正在添加中请稍后...",
				spinner: "el-icon-loading",
				background: "rgba(0, 0, 0, 0.7)",
			});
			/**
			 * @desc 处理传递到后端接口的数据
			 */
			let postdata = {
				sort_name: this.addCourseSortData.name,
				sort_desc: this.addCourseSortData.desc,
			};

			request({
				/* 请求地址 */
				url: "/vue-admin-template/course/sort/add",
				/* 请求方式 */
				method: "post",
				/* 请求传参 */
				postdata,
				/* .then()请求成功的回调 */
				/* 
					1、提示用户，
					2、关闭loading
					3、清空弹窗内容
					4、关闭弹窗
					5、刷新当前数据表格
				*/
			})
				.then(() => {
					setTimeout(() => {
						this.$message({
							message: "教学分类添加成功",
							type: "success",
						});
						// 关闭loading
						loading.close();
						// 关闭弹窗
						this.addCourseSortData.dialogVisible = false;
						// 清空弹窗数据
						this.addCourseSortData.name = "";
						this.addCourseSortData.desc = "";
					});
					/* 请求失败的回调 */
				})
				.catch(() => {
					setTimeout(() => {
						this.$message({
							message: "教学分类添加失败，请稍后再试~",
							type: "error",
						});
						// 关闭lading
						loading.close();

						// 关闭添加弹窗
						this.addCourseSortData.dialogVisible = false;
						// 清空弹窗数据
						this.addCourseSortData.name = "";
						this.addCourseSortData.desc = "";
					});
				});
		},
		/**
		 * @desc 取消添加
		 */
		handleAddCourseSortDataCancel() {
			// 关闭添加弹窗
			this.addCourseSortData.dialogVisible = false;
			// 清除弹窗数据
			this.addCourseSortData.name = "";
			this.addCourseSortData.desc = "";
		},
		/**
		 * @description 处理关闭添加教学分类
		 */
		handleAddCourseSortDataClose() { },
		/**
		 * @desc 编辑教学分类
		 */
		// editCourseSortData: {
		// 		dialogVisible: false,
		// 		id: "",
		// 		name: "",
		// 		desc: ""
		// 	},
		editCourseSort(data) {
			console.log("当前教学分类数据:", data);
			// 编辑弹窗赋值
			this.editCourseSortData.id = data.row.sort_id;
			this.editCourseSortData.name = data.row.sort_name;
			this.editCourseSortData.desc = data.row.sort_desc;
			// 打开编辑弹窗
			this.editCourseSortData.dialogVisible = true;
		},
		/**
		 * @desc 确定编辑教学分类
		 */
		handleEditCourseSortDataConfirm() {
			if (this.editCourseSortData.name == "") {
				this.$message({
					message: "教学分类名称不能为空。",
					type: "error",
				});
				return;
			}
			if (this.editCourseSortData.desc == "") {
				this.$message({
					message: "教学分类描述不能为空。",
					type: "error",
				});
				return;
			}
			const loading = this.$loading({
				lock: true,
				text: "正在修改中请稍后...",
				spinner: "el-icon-loading",
				background: "rgba(0, 0, 0, 0.7)",
			});
			/**FF
			 * @desc 处理编辑分类的postdata
			 */
			let postdata = {
				sort_id: this.editCourseSortData.sort_id,
				sort_name: this.editCourseSortData.name,
				sort_desc: this.editCourseSortData.desc,
			};
			request({
				/* 请求地址 */
				url: "/vue-admin-template/course/sort/edit",
				/* 请求方式 */
				method: "post",
				/* 请求传参 */
				postdata,
				/* .then()请求成功的回调 */
				/* 
					1、提示用户，
					2、关闭loading
					3、清空弹窗内容
					4、关闭弹窗
					5、刷新当前数据表格
				*/
			})
				.then(() => {
					setTimeout(() => {
						this.$message({
							message: "教学分类添加成功",
							type: "success",
						});
						// 关闭loading
						loading.close();
						// 关闭编辑弹窗
						this.editCourseSortData.dialogVisible = false;
						// 清理数据
						this.editCourseSortData.id = "";
						this.editCourseSortData.name = "";
						this.editCourseSortData.desc = "";
					});
					/* 请求失败的回调 */
				})
				.catch(() => {
					this.$message({
						message: "教学分类添加失败",
						type: "error",
					});
					// 关闭loading
					loading.close();
					// 关闭编辑弹窗
					this.editCourseSortData.dialogVisible = false;
					// 清除编辑弹窗数据
					this.editCourseSortData.id = "";
					this.editCourseSortData.name = "";
					this.editCourseSortData.desc = "";
				});
		},
		/**
		 * @desc 取消编辑
		 */
		handleEditCourseSortDataCancel() {
			this.editCourseSortData.dialogVisible = false;
		},
		/**
		 * @description 关闭弹窗编辑之前的事件
		 */
		handleEditCourseSortDataClose() { },
		/**
		 * @desc 确认事件
		 * @from 标识是来自哪个事件的确认事件
		 * @content 需要提示用户的内容
		 * @title 确认弹窗标题
		 */
		handleConfirm(from, content, title) {
			this.confirmDialogData.title = title;
			this.confirmDialogData.content = content;
			this.confirmDialogData.from = from;
			this.confirmDialogData.dialogVisible = true;
		},
		/**
		 * @description 确定取消
		 */
		handleEditConfirmDialogCancel() {
			this.confirmDialogData.dialogVisible = false;
			// 清除确定弹窗的内容，避免下次确定数据混乱
			this.confirmDialogData.title = "";
			this.confirmDialogData.content = "";
			this.confirmDialogData.from = "";
		},
		/**
		 * @desc 确定
		 */
		handleConfirmDialogConfirm() {
			// 如果是批量删除
			if (this.confirmDialogData.from === "multipleDelete") {
				// loading 开启
				const loading = this.$loading({
					lock: true,
					text: "正在进行批量删除操作...",
					spinner: "el-icon-loading",
					background: "rgba(0, 0, 0, 0.7)",
				});
				let temp = getSelectData();
				let arr = temp.map((item) => {
					return item.sort_id;
				});
				/**
				 * @desc 处理传递到后端接口的数据
				 */
				let postdata = {
					data: arr,
				};

				request({
					/* 请求地址 */
					url: "/vue-admin-template/course/sort/bach_delete",
					/* 请求方式 */
					method: "post",
					/* 请求传参 */
					postdata,
					/* .then()请求成功的回调 */
					/* 
					1、提示用户，
					2、关闭loading
					3、清空弹窗内容
					4、关闭弹窗
					5、刷新当前数据表格
				*/
				})
					.then(() => {
						setTimeout(() => {
							this.$message({
								message: "批量删除教学分类成功",
								type: "success",
							});
							// 关闭loading
							loading.close();
							// 关闭弹窗
							this.confirmDialogData.dialogVisible = false;
							// 清空弹窗数据
							this.confirmDialogData.title = "";
							this.confirmDialogData.content = "";
							this.confirmDialogData.from = "";
						});
						/* 请求失败的回调 */
					})
					.catch(() => {
						setTimeout(() => {
							this.$message({
								message: "批量删除教学分类失败",
								type: "error",
							});
							// 关闭lading
							loading.close();

							// 关闭添加弹窗
							this.confirmDialogData.dialogVisible = false;
							// 清空弹窗数据
							this.confirmDialogData.title = "";
							this.confirmDialogData.content = "";
							this.confirmDialogData.from = "";
						});
					});
			} else if (this.confirmDialogData.from === "delete") {
				// loading 开启
				const loading = this.$loading({
					lock: true,
					text: "正在进行批量删除操作...",
					spinner: "el-icon-loading",
					background: "rgba(0, 0, 0, 0.7)",
				});
				let temp = getSelectData();
				let arr = temp.map((item) => {
					return item.sort_id;
				});
				/**
				 * @desc 处理传递到后端接口的数据
				 */
				let postdata = {
					data: arr,
				};

				request({
					/* 请求地址 */
					url: "/vue-admin-template/course/sort/delete",
					/* 请求方式 */
					method: "post",
					/* 请求传参 */
					postdata,
					/* .then()请求成功的回调 */
					/* 
					1、提示用户，
					2、关闭loading
					3、清空弹窗内容
					4、关闭弹窗
					5、刷新当前数据表格
				*/
				})
					.then(() => {
						setTimeout(() => {
							this.$message({
								message: "删除教学分类成功",
								type: "success",
							});
							// 关闭loading
							loading.close();
							// 关闭弹窗
							this.confirmDialogData.dialogVisible = false;
							// 清空弹窗数据
							this.confirmDialogData.title = "";
							this.confirmDialogData.content = "";
							this.confirmDialogData.from = "";
						});
						/* 请求失败的回调 */
					})
					.catch(() => {
						setTimeout(() => {
							this.$message({
								message: "删除教学分类失败",
								type: "error",
							});
							// 关闭lading
							loading.close();

							// 关闭添加弹窗
							this.confirmDialogData.dialogVisible = false;
							// 清空弹窗数据
							this.confirmDialogData.title = "";
							this.confirmDialogData.content = "";
							this.confirmDialogData.from = "";
						});
					});
			}
		},
		/**
		 * @desc 批量删除
		 */
		multipleDelete() {
			handleConfirm(
				"multipleDelete",
				"确认批量删除选中的分类吗？",
				"批量删除确认"
			);
		},
		/**
		 * @desc 删除
		 */
		deleteCourseSort(row) {
			let content = `确认删除选中的分类: [${row.row.sort_id}] ${row.row.sort_name}吗？`;
			handleConfirm("delete", content, "删除确认");
		},
		/**
		 * @desc 导出
		 */
		exportCourseExcel() {
			// 创建工作簿和工作表
			const wb = XLSX.utils.book_new();
			const ws = XLSX.utils.json_to_sheet(this.courseSortList);
			XLSX.utils.book_append_sheet(wb, ws, "Sheet1");

			// 生成Excel文件并保存
			const wbout = XLSX.write(wb, {
				bookType: "xlsx",
				type: "array",
			});
			try {
				saveAs(
					new Blob([wbout], {
						type: "application/octet-stream",
					}),
					"table_data.xlsx"
				);
			} catch (e) {
				if (typeof console !== "undefined") {
					console.log(e, wbout);
				}
			}
			return wbout;
		},
		/**
		 * @desc 查询数据
		 */
		filter() {
			// 判断用户是否输入搜索信息
			if (this.courseSortName == "") {
				this.$message({
					message: "请输入筛选条件",
					type: "error",
				});
				return;
			}
			// loading 开启
			const loading = this.$loading({
				lock: true,
				text: "正在加载数据，请耐心等待...",
				spinner: "el-icon-loading",
				background: "rgba(0, 0, 0, 0.7)",
			});
			//   深拷贝避免数据影响
			let data = JSON.parse(JSON.stringify(this.courseSortList));
			//   将当前页数据置空
			this.currentPageData = [];
			this.filterData = data.filter((item) => {
				if (item.sort_name.indexOf(this.courseSortName) !== -1) {
					return item;
				}
			});
			// 分页器数据恢复初始化
			this.currentPage = 1;
			this.currentPageSize = 1;
			this.currentPageData = this.filterData.slice(0, 10);
		},
		/**
		 * @desc 刷新
		 */
		refresh() {
			/**
			 * @todo
			 * 1、恢复初始化数据
			 */
			this.currentPage = 1;
			this.init();
		},
		/**
		 * @handleSizeChange  page-size 改变时触发
		 * @参数 新每页条数
		 */
		handleSizeChange(data) {
			this.currentPageData = this.filterData.slice(
				(this.currentPage - 1) * data,
				data * this.currentPage
			);
		},
		/**
		 * @desc 监听当前页大小改变
		 */
		handleCurrentChange(data) {
			this.currentPageData = this.filterData.slice(
				(data - 1) * this.currentPageSize,
				this.currentPageSize * data
			);
		},
	},
};
</script>
<style lang="scss" scoped>
.theoretical-teaching-sort {
	padding: 20px 10px;

	.operation {
		// border: 1px solid red;
		box-sizing: border-box;
		display: flex;
		justify-content: space-between;
		height: 40px;
		line-height: 40px;
		margin-bottom: 20px;
	}

	.op {
		display: flex;
		justify-self: start;
	}

	.collect {
		display: flex;
		justify-content: flex-start;
	}

	.collect .collect-item {
		margin-right: 20px;
	}

	.pagination {
		margin-top: 20px;
		float: right;
	}
}
</style>
